<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button type="primary" @click="addDialogShow = true; ">新增</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="condition.name" placeholder="请输入要搜索的名称" @input="selectByPage(1)"/>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-select
                v-model="condition.status"
                placeholder="请选择是否上架"
                clearable
                :value-on-clear="null"
                style="width: 200px"
                @change="selectByPage(1)"
            >
              <el-option label="上架" value="1"/>
              <el-option label="下架" value="0"/>
            </el-select>
          </el-form-item>

          <el-form-item style="float: right;">
            <el-select
                v-model="condition.parentId"
                placeholder="请选择父分类"
                clearable
                :value-on-clear="null"
                style="width: 200px"
                @change="selectByPage(1)"
            >
              <el-option label="父级" value="0"/>
              <el-option v-for="(parent, index) in allParent" :key="index" :label="parent.name" :value="parent.id"/>
            </el-select>
          </el-form-item>

        </el-form>
        <el-table :data="pageInfo.list" border>
          <el-table-column prop="id" label="ID"/>
          <el-table-column prop="name" label="名称"/>
          <el-table-column label="图片">
            <template #default="scope">
              <el-avatar shape="square" :size="50" :src="SERVER_ADDR + '/category/pic/' + scope.row.pic"/>
            </template>
          </el-table-column>
          <el-table-column prop="dscp" label="描述"/>
          <el-table-column label="父分类">
            <template #default="scope">
              <el-text class="mx-1" type="primary" v-if="scope.row.parent">{{ scope.row.parent.name }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="是否推荐">
            <template #default="scope">
              <el-tag type="primary" v-if="scope.row.recom == 1">推荐</el-tag>
              <el-tag type="warning" v-if="scope.row.recom == 0">不推荐</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否上架">
            <template #default="scope">
              <el-tag type="primary" v-if="scope.row.status == 1">上架</el-tag>
              <el-tag type="warning" v-if="scope.row.status == 0">下架</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="140">
            <template #default="scope">
              <el-button size="small" type="primary" @click="selectById(scope.row.id)">
                修改
              </el-button>
              <el-popconfirm title="你确定要删除该分类吗?"
                             confirm-button-text="确认"
                             cancel-button-text="取消" width="200px"
                             @confirm="deleteCategory(scope.row.id)">
                <template #reference>
                  <el-button size="small" type="danger">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--<el-row class="row-bg" justify="center">-->
        <!--  <el-pagination style="margin-top: 20px;" background layout="prev, pager, next" :total="pageInfo.total"-->
        <!--                 :page-size="pageInfo.pageSize" @change="selectByPage"/>-->
        <!--</el-row>-->
        <el-row class="row-bg" justify="center">
          <el-pagination style="margin-top: 20px;" background layout="prev, pager, next"
                         v-model:current-page="pageInfo.pageNum"
                         :page-count="pageInfo.pages"
                         @update:current-page="selectByPage"/>
        </el-row>
      </el-card>
    </el-col>
  </el-row>

  <!-- 新增分类对话框开始 -->
  <el-dialog v-model="addDialogShow" title="新增分类" width="500">
    <el-form>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="categoryAdd.name" placeholder="请输入名称" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="categoryAdd.dscp" placeholder="请输入描述" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="父分类" label-width="20%">
        <el-select v-model="categoryAdd.parentId" clearable :empty-values="[0]" :value-on-clear="0"
                   placeholder="请选择分类" style="width: 300px;">
          <el-option v-for="(category, index) in allParent" :key="index" :label="category.name"
                     :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="categoryAdd.recom">
          <el-radio label="推荐" :value="1" size="large"/>
          <el-radio label="不推荐" :value="0" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="categoryAdd.status">
          <el-radio label="上架" :value="1" size="large"/>
          <el-radio label="下架" :value="0" size="large"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="图片" label-width="20%">
        <el-upload class="avatar-uploader" :action="SERVER_ADDR + '/category/upload'" name="pic" :headers="headers"
                   :show-file-list="false" :on-success="handleSuccessAdd" :before-upload="beforeAdd">
          <img v-if="categoryAdd.pic" :src="SERVER_ADDR + '/category/pic/' + categoryAdd.pic " class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">取消</el-button>
        <el-button type="primary" @click="insert">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--新增分类的对话框结束-->

  <!-- 修改分类对话框开始 -->
  <el-dialog v-model="uploadDialogShow" title="修改分类" width="500">
    <el-form>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="categoryUpload.name" placeholder="请输入名称" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="categoryUpload.dscp" placeholder="请输入描述" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="父分类" label-width="20%">
        <el-select v-model="categoryUpload.parentId" clearable :empty-values="[0]" :value-on-clear="0"
                   placeholder="请选择分类" style="width: 300px;">
          <el-option v-for="(category, index) in allParent" :key="index" :label="category.name"
                     :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="categoryUpload.recom">
          <el-radio label="推荐" :value="1" size="large"/>
          <el-radio label="不推荐" :value="0" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="categoryUpload.status">
          <el-radio label="上架" :value="1" size="large"/>
          <el-radio label="下架" :value="0" size="large"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="图片" label-width="20%">
        <el-upload class="avatar-uploader" :action="SERVER_ADDR + '/category/upload'" name="pic" :headers="headers"
                   :show-file-list="false" :on-success="handleSuccessUpload" :before-upload="beforeUpload">
          <img v-if="categoryUpload.pic" :src="SERVER_ADDR + '/category/pic/' + categoryUpload.pic " class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="uploadDialogShow = false">取消</el-button>
        <el-button type="primary" @click="update">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改分类的对话框结束-->

</template>

<script setup>
import categoryApi from "@/api/categoryApi.js"
import {computed, ref} from "vue";
import {ElMessage} from "element-plus";
import {useTokenStore} from "@/stores/token.js";

const tokenStore = useTokenStore();

const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return {
    token
  }
});

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);

//新增 上传图片之前的回调
function beforeAdd(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M');
    return false
  }
  return true;
}

//修改 上传图片之前的回调
function beforeUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M');
    return false
  }
  return true;
}

//新增 成功上传之后的回调
function handleSuccessAdd(resp) {
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    categoryAdd.value.pic = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}

//修改 成功上传之后的回调
function handleSuccessUpload(resp) {
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    categoryUpload.value.pic = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}

//添加分类
function insert() {
  categoryApi.insert(categoryAdd.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //隐藏对话框
          addDialogShow.value = false;
          //清空对话框
          categoryAdd.value = {
            name: null,
            dscp: null,
            pic: null,
            parentId: 0,
            recom: 1,
            status: 1
          };
          //查询第一页
          selectByPage(1);
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

//修改分类
function update() {
  categoryApi.update(categoryUpload.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //隐藏对话框
          uploadDialogShow.value = false;
          //查询当前页
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}

//删除分类
function deleteCategory(id) {
  categoryApi.delete(id)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //查询第一页
          selectByPage(1);
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

//根据id查询被修改分类的信息
function selectById(id) {
  categoryApi.selectById(id)
      .then(resp => {
        categoryUpload.value = resp.data;
        uploadDialogShow.value = true;
      })
}

//搜索条件
const condition = ref({
  name: null,
  parentId: null,
  status: null
});

//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});

//分页查询
function selectByPage(pageNum) {
  categoryApi.selectByPage(condition.value, pageNum, 5)
      .then(resp => {
        pageInfo.value = resp.data;
      });
}

//父分类
const allParent = ref([]);

//获取所有父分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        allParent.value = resp.data;
      });
}

//被添加的分类信息
const categoryAdd = ref({
  name: null,
  dscp: null,
  pic: null,
  parentId: 0,
  recom: 1,
  status: 1
});

//被修改的分类信息
const categoryUpload = ref({
  id: null,
  name: null,
  dscp: null,
  pic: null,
  parentId: 0,
  recom: 1,
  status: 1
});

//是否显示添加对话框
const addDialogShow = ref(false);

//是否显示修改对话框
const uploadDialogShow = ref(false);

selectAllParent();
selectByPage(1);
</script>

<style scoped>
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>